{% extends "base.html" %}
{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

{% block title %}Meter Rate Plan History: {{ meter.meter_id }}{% endblock %}

{% block content %}
<div class="container">

  {% include "core/_breadcrumbs.html" %}

  <div class="card mb-3" id="rateplanhistory">
    <div class="card-body">
      {% if meter.description %}
        <h2>Meter Rate Plan History for {{ meter.description }}</h2>
      {% else %}
        <h2>Meter Rate Plan History for {{ meter.meter_id }}</h2>
      {% endif %}
      <br/>
      {% block inner_content %}

      <h3>Get Rates from OpenEI Utility Rate Database:</h3>
      <div class="form-group">
        <label for="onDate">Effective as of Date*</label>
        <b-form-input type="text" class="datetime" id="onDate" placeholder="Input Date" :state="onDateState" v-model="onDate" required></b-form-input>
        <b-form-invalid-feedback id="onDate">
            Effective as of Date is required
        </b-form-invalid-feedback>
      </div>
      <div class="text-right">
        <b-button v-if="!isSearchDisabled" variant="primary" v-on:click.stop.prevent="get_utility_rates()" :disabled="isSearchDisabled">
          <i class="fa fa-search"></i> Search
        </b-button>
        <b-spinner v-if="isSearchDisabled" variant="secondary"></b-spinner>
      </div>

      <div class="mt-3" v-if="rates.length">
          <select name="util_rate" class="select form-control" id="id_util_rate" v-model="selectedRate">
            <option v-for="c in rates" :value="c.value">${ c.name }</option>
          </select>
          <div class="mt-3 text-right">
            <b-button variant="primary" v-on:click.stop.prevent="add_utility_rate()" :disabled="isAddDisabled">
              <i class="fa fa-plus"></i> Add Rate
            </b-button>
          </div>
      </div>

      <div class="alert alert-danger mt-3" role="alert" v-if="errors.error">
          ${ errors.error }
      </div>

      <div class="mt-3" v-if="meterRatePlans.length">
        <b-table-lite striped hover :items="meterRatePlans" :fields="fields">
            <template v-slot:cell(edit)="item">
              <a class="btn btn-outline-primary btn-sm  ml-1" :href="get_rate_plan_history_edit_url(item)"><i class="fas fa-edit"></i></a>
            </template>
            <template v-slot:cell(del)="item">
              <button v-confirm:click.stop.prevent="delete_meter_rate_plan_history(item.index)" class="btn btn-outline-danger btn-sm  ml-1"><i class="fas fa-trash"></i></button>
            </template>
            <template v-slot:cell(description)="item">
                <a :href="get_rate_plan_history_detail_url(item)">${ item.item.description }</a>
            </template>
        </b-table-lite>
      </div>

      {% endblock inner_content %}
    </div>
  </div>

</div>
<script>
(function() {
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';

  new Vue({
    delimiters: ['${', '}'],
    name: 'rateplanhistory',
    el: '#rateplanhistory',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        onDateState: null,
        onDate: moment().format('YYYY-MM-DD HH:mm:ss'),
        errors: {'error': null},
        rates: [],
        meterRatePlans: [],
        selectedRate: null,
        meterId: {%if meter_id %}'{{ meter_id|safe}}'{%else%}''{%endif%},
        isSearchDisabled: false,
        isAddDisabled: false,
        fields: [
          {
            key: 'rate_plan_history_id',
            label: 'ID'
          },
          {
            key: 'description',
            label: 'Description'
          },
          {
            key: 'from_datetime',
            label: 'From'
          },
          {
            key: 'thru_datetime',
            label: 'Thru'
          },
          {
            key: 'edit',
            label: '',
            'class': 'text-right'
          },
          {
            key: 'del',
            label: '',
            'class': 'text-right'
          },
        ],

      }
    },
    mounted() {
      console.log('mounted..');
      this. get_meter_rate_plan_history_list();
      flatpickr(this.$el.getElementsByClassName('datetime'), {
            "dateFormat": "Y-m-d H:i:S",
            "time_24hr": "true",
            "allowInput": "true",
            "enableTime": "true",
            "enableSeconds": "true",
            "minuteIncrement": 1});
    },
    methods: {
      get_utility_rates() {
        console.log('get_utility_rates..');
        this.onDateState = null;
        this.errors = {'error': null};
        if (!this.onDate) {
            this.onDateState = false;
        } else {
            this.isSearchDisabled = true;
            url = dutils.urls.resolve('utility_rates_json') + '?meter_id=' + this.meterId + '&on_date=' + this.onDate;
            axios.get(url)
              .then(x => {
                console.log('get_utility_rates', x.data)
                if (x.data.error) {
                    this.errors['error'] = x.data.error;
                } else if (!x.data.items || (x.data.items && x.data.items.length == 0)) {
                    this.errors['error'] = 'There are no utility rates found.';
                } else {
                    this.rates = x.data.items;
                    this.selectedRate = this.rates[0].value;
                }
                this.isSearchDisabled = false;
              })
              .catch(err => {
                console.error('loading utility rates error :', err);
                e = getResponseError(err);
                this.errors = e;
                this.isSearchDisabled = false;
              });
        }

      },
      add_utility_rate() {
        this.errors = {'error': null};
        url = dutils.urls.resolve('meter_rate_plan_history');
        console.log('add_utility_rate: this.selectedRate', this.selectedRate)
        if (!this.selectedRate) {
            this.errors = {'error': 'Please, select Rate Plan.'};
        } else {
            this.isAddDisabled = true;
            data = {meter_id: this.meterId, page_label: this.selectedRate}
            axios.post(url, data, {headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
              .then(x => x.data)
              .then(x => {
                if (x.success) {
                  console.log('add_utility_rate, result = ', x);
                  this. get_meter_rate_plan_history_list();
                }
                this.isAddDisabled = false;
              })
              .catch(err => {
                e = getResponseError(err);
                console.error(e, err);
                this.errors = e;
                this.isAddDisabled = false;
              });
        }
      },
      get_meter_rate_plan_history_list() {
        console.log('get_meter_rate_plan_history_list..');
        this.errors = {'error': null};
        url = dutils.urls.resolve('meter_rate_plan_history') + '?meter_id=' + this.meterId;
        axios.get(url)
          .then(x => {
            console.log('get_meter_rate_plan_history_list', x.data);
            if (x.data.error) {
                this.errors['error'] = x.data.error;
            } else if (x.data.items && x.data.items.length > 0) {
                this.meterRatePlans = x.data.items;
            } else {
                this.meterRatePlans = [];
            }
          })
          .catch(err => {
            console.error('loading meter_rate_plan_history_list error :', err);
            e = getResponseError(err);
            this.errors = e;
          });
      },
      delete_meter_rate_plan_history(index) {
        return {
          okText: 'Delete',
          ok: dialog => this.delete_meter_rate_plan_history_cb(dialog, index),
          message: 'Are you sure?'
        }
      },
      delete_meter_rate_plan_history_cb(dialog, index) {
        dialog.close();
        console.log('delete_meter_rate_plan_history_cb, index = ', index);
        rate_plan_history_id = this.meterRatePlans[index].rate_plan_history_id;
        url = dutils.urls.resolve('meter_rate_plan_history');
        axios.delete(url, {data: {rate_plan_history_id: rate_plan_history_id}, headers: {'X-CSRFToken': this.csrfmiddlewaretoken}})
            .then(x => x.data)
            .then(x => {
              console.log('delete_meter_rate_plan_history_cb Done', x);
              if (x.success) {
                this. get_meter_rate_plan_history_list();
              }
            })
            .catch(err => {
              e = getResponseError(err);
              console.error(e, err);
              this.errors = e;
            });
      },
      get_rate_plan_history_detail_url(item) {
        return dutils.urls.resolve('meter_rate_plan_history_detail', { rate_plan_history_id: item.item.rate_plan_history_id })
      },
      get_rate_plan_history_edit_url(item) {
        return dutils.urls.resolve('meter_rate_plan_history_edit', { rate_plan_history_id: item.item.rate_plan_history_id })
      }
    }
  });
})();
</script>
{% endblock content %}
